package com.unhz.taigu.controller.system;

import com.unhz.generator.pojo.SysPermission;
import com.unhz.generator.pojo.SysRole;
import com.unhz.generator.pojo.SysRolePermission;
import com.unhz.generator.utils.EmptyUtil;
import com.unhz.generator.utils.JsonResult;
import com.unhz.generator.utils.Page;
import com.unhz.generator.utils.PageSize;
import com.unhz.taigu.controller.shiro.CustomRealm;
import com.unhz.taigu.service.SysPermissionService;
import com.unhz.taigu.service.SysRoleService;
import com.unhz.taigu.service.rolepermission.RolePermissionService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.List;

@Controller
@RequestMapping("/sysRoleController")
public class SysRoleController {

    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private CustomRealm customRealm;
    @Autowired
    private SysPermissionService sysPermissionService;
    @Autowired
    private RolePermissionService rolePermissionService;

    @RequestMapping("/findAllRole")
    @RequiresPermissions("role:findAll")
    public String findAllRole(Model model
                              ,@RequestParam(value = "pageNo",defaultValue = "1",required = false)String pageNo,
                              @RequestParam(value = "keywords",defaultValue = "",required = false)String keywords,
                              HttpServletRequest request) throws UnsupportedEncodingException {
        if("GET".equals(request.getMethod())){
            keywords = new String(keywords.getBytes("iso-8859-1"),"utf-8");
        }
        List<SysRole> sysRoleList = sysRoleService.findAllRole();
        Page<SysRole> page = sysRoleService.findPageRole(pageNo, PageSize.pageSize, keywords);
        model.addAttribute("page",page);
        model.addAttribute("keywords",keywords);
        return "system/role/role-list.jsp";

    }

    //todo 删出（涉及到权限的修改）
    @RequestMapping("/toAdd")
    @RequiresPermissions("role:add")
    public String toAdd(){
        return "system/role/role-add.jsp";
    }
    @RequestMapping("/insert")
    @RequiresPermissions("role:add")
    public String insert(SysRole sysRole){
        String index = sysRoleService.insertRole(sysRole);
        return "redirect:findAllRole";
    }
    //跳转到修改页面
    @RequestMapping("/toUpdate")
    @RequiresPermissions("role:update")
    public String toUpdate(@RequestParam("roleId")Integer roleId,Model model){
        SysRole sysRole = sysRoleService.selectByRoleId(roleId);
        model.addAttribute("role", sysRole);
        return "system/role/role-update.jsp";
    }
    //执行修改
    @RequestMapping("/update")
    @RequiresPermissions("role:update")
    public String update(SysRole sysRole){
        String index = sysRoleService.updateRole(sysRole);
        return "redirect:findAllRole";
    }

    //查询角色权限菜单
    @RequestMapping("/findPermission")
    public String findPermission(Model model,@RequestParam("roleId") Integer roleId){

        SysRole sysRole = sysRoleService.selectByRoleId(roleId);
        //查询所有的权限
        List<SysPermission> sysPermissionList = sysPermissionService.selectPermission();
        //查询所有的菜单
        List<SysPermission> menusList = sysPermissionService.selectMenus();
        //应该查询角色是否有权限啊
        List<SysPermission> userpermission = sysPermissionService.selectPermissionByRoleId(roleId);
        //查询用户菜单（如果角色用户没有一个权限,进行品判断啊！）
        List<SysPermission> usermenus = sysPermissionService.selectMenusByRoleId(roleId);
        //todo 区分用户拥有的权限
        for(SysPermission sysPermission : sysPermissionList){
            sysPermission.setChangeId(1);
        }
        if(!EmptyUtil.isEmpty(userpermission)){
            for(SysPermission sysPermission : userpermission){
                sysPermission.setChangeId(2);
            }
            for(SysPermission sysPermission : sysPermissionList){
                for(SysPermission sysPermission1 : userpermission){
                    if(sysPermission.getId() == sysPermission1.getId()){
                        sysPermission.setChangeId(2);
                    }
                }
            }
        }
        //todo 区分用户拥有的菜单
        for(SysPermission sysPermission : menusList){
            sysPermission.setChangeId(1);
        }
        if(!EmptyUtil.isEmpty(usermenus)){
            for(SysPermission sysPermission : usermenus){
                sysPermission.setChangeId(2);
            }
            for(SysPermission sysPermission : menusList){
                for(SysPermission sysPermission1 : usermenus){
                    if(sysPermission.getId() == sysPermission1.getId()){
                        sysPermission.setChangeId(2);
                    }
                }
            }
        }
        model.addAttribute("permissionList", sysPermissionList);
        model.addAttribute("menuList",menusList);
        model.addAttribute("role", sysRole);

        return "system/quanxian/quanxianPermission-update.jsp";
    }



    //执行权限功能
    //修改角色信息
    @RequestMapping("/updateRole")
    public String updatePart(Model model, SysRole sysRole,
                             @RequestParam("roleId")Integer roleId,
                             @RequestParam("roleName")String roleName,
                             @RequestParam("menuids")String menuids,
                             @RequestParam("permissionids")String permissionids, HttpServletRequest request, HttpServletResponse response){

        SysRole rl = new SysRole();
        rl.setId(roleId);
        rl.setRoleName(roleName);
        String index = sysRoleService.updateRole(rl);
        //String index = partService.updatePart(pt);
        if(index.equals("success")){

        }
        //只能总管理员给子管理员的权限，不能随便修改
        if(roleId != 1 && !roleId.equals(1)){
            int num=0;
            //修改权限
            //1.根据角色的id删除他已有的权限
            int count = rolePermissionService.deleteByRoleId(roleId);
            if(count>0){

            }
            String[] menuid = menuids.split(",");
            String[] permissionid = permissionids.split(",");
            //2.循环添加角色的权限(菜单权限和权限表的权限)
            SysRolePermission rps = null;
            for(int i=0;i<menuid.length;i++){
                //循环添加菜单
                rps = new SysRolePermission();
                rps.setRoleId(roleId);
                rps.setPermissionId(Integer.parseInt(menuid[i]));
                num = rolePermissionService.insertRolePermission(rps);
            }
            for(int i=0;i<permissionid.length;i++){
                //循环添加权限
                rps = new SysRolePermission();
                rps.setRoleId(roleId);
                rps.setPermissionId(Integer.parseInt(permissionid[i]));
                num = rolePermissionService.insertRolePermission(rps);
            }
            if(num>0){
                //修改权限成功清空缓存
                customRealm.clearCached();
            }
        }
        return "redirect:findAllRole";
    }

    //添加权限

    @RequestMapping("/toAddRole")
    public String tooinsert(Model model){
        //查询所有的权限
        //查询所有的权限
        List<SysPermission> sysPermissionList = sysPermissionService.findAllPermission();
        //查询所有的菜单
        List<SysPermission> menusList = sysPermissionService.findAllChild();
        model.addAttribute("permissionList", sysPermissionList);
        model.addAttribute("menusList",menusList);
        return "system/role/rolePermission-add.jsp";
    }


   //删除角色(联合删除表的数据)

    @RequestMapping("/delete")
    @RequiresPermissions("role:delete")
    @ResponseBody
    public JsonResult delete(@RequestParam("roleId")Integer roleId){
         //删除角色权限表
         rolePermissionService.deleteByRoleId(roleId);
         //删除角色
         int count = sysRoleService.delete(roleId);
         if(count > 0){
             return JsonResult.success("删除成功");
         }
         return JsonResult.failure("删除失败!!");
    }



}
